<?php
/**
 * @author ranlv
 * @abstract 购物车
 * @param 2016-04-01
 */
namespace liketry\controllers;

use yii;
use services\models\Cart;
use services\models\Product;
use services\models\GoodsDetail;
use services\models\ProductDetail;
use services\models\ProductStock;
use services\models\Goods;
use services\models\discount\FullCut;
use services\models\Order;
use services\models\OrderDiscount;

class CartController extends CustomController
{
    public $maxNumber = 0;
    
    public function beforeAction($action) {
       $this->maxNumber = Yii::$app->params['maxNumber'];
       return  parent::beforeAction($action);
    }
    
    
    private static function  formatDecimal($money){
        return Yii::$app->formatter->asDecimal($money,2);
    }
    
    
    public static function cartIdsProc($cart_ids)
    {
        return array_filter(explode(',', $cart_ids), function ($v) {
            if (!$v || !preg_match('/^\d+$/', $v)) {
                return false;
            }
            return true;
        });
    }
    
    
    public function actionIndex()
    {   
        $msg = ['flag'=>false,'msg'=>'','data'=>'','errCode'=>''];
        $data = [];
        $cartInfos = Cart::findAll(['bestry_uid'=>$this->bestry_uid]);
        if(!empty($cartInfos)) {
            foreach ($cartInfos as $key=>$item) {
                
                $status = true;//当前商品是否失效
                $size = 1;//前端可输入最大值
                
                //获取商品详情
                $goods_info = GoodsDetail::findByGoodsId($item->goods_id);
                if(!$goods_info) continue;
                
                //获取产品规格描述
                $Product_detail_info = ProductDetail::findByProductId($item->product_id);
                
                //  取产品信息
                $prodcut_info = Product::findByProductId($item->product_id,true,false);
                if(!$prodcut_info) continue;
                //取库存信息
                $prodcut_stock_info = ProductStock::findByProductId($item->product_id);
                if(!$prodcut_stock_info) continue;
                
                $info =  Goods::findByGoodsId($item->goods_id);
                
                $goodPic = Goods::findByGoodsIdFromRedis($item->goods_id,['pic']);
                
                //组织data
                $data[$key]['cart_id'] = $item->cart_id;
                $data[$key]['pic'] = Yii::$app->params['goods_image_url'].str_replace('./upload', 'upload', $goodPic['pic']);
                $data[$key]['goods_name'] = $goods_info['goods_name'];
                $data[$key]['number'] = $item->number;
                $data[$key]['product_id'] = $item->product_id;
                $data[$key]['goods_id'] = $item->goods_id;
                $data[$key]['type_name'] = $prodcut_info['type'] == Product::$_TYPE_TRY ? '试用' : '购买';
                $data[$key]['price_type'] = $prodcut_info['price_type'];
                $data[$key]['price'] = $prodcut_info['price_type'] == Product::$_PRICE_TYPE_RMB ? $prodcut_info['sale_price'] : $prodcut_info['try_price'] ;
                $data[$key]['free_post'] = $goods_info['free_post'];
                $size = 0;
                if($prodcut_info['type'] == Product::$_TYPE_TRY) {
                    $size = 1;
                }elseif(($prodcut_stock_info['stock'] > $this->maxNumber) && $prodcut_info['type'] == Product::$_TYPE_SALE) {
                    $size = $this->maxNumber;
                } else {
                    $size = $prodcut_stock_info['stock'];
                }
                $data[$key]['size'] = $size;
                //库存为0
                if((empty($prodcut_stock_info) || $prodcut_stock_info['stock'] < 1)){
                    $status =false;
                }
                //规格下线
                if($prodcut_info['sale_status'] == Product::$_SALE_STATUS_OFF_SHELF) {
                    $status =false;
                }
                //商品下线 
                /* if($info['status'] == Goods::$_STATUS_OFF) {
                    $status =false;
                } */
                
                $data[$key]['status'] = $status;
                
                //取规格信息
                $spec_arr = [];
                $temp_guige = explode(',',  $Product_detail_info['spec_desc']);
                
                if(!empty($temp_guige[0])) {
                    foreach ($temp_guige as $k=>$val) {
                        $arr = explode(':', $val);
                        $spec_arr[$k]['name']= $arr[0];
                        $spec_arr[$k]['value'] = $arr[1];
                    }
                }
                
                $data[$key]['spec_desc'] = $spec_arr;
                
                if($prodcut_info['price_type'] == Product::$_PRICE_TYPE_RMB) {
                    $data[$key]['totoal_price'] = ($data[$key]['price']  * $item->number);
                }else {
                    $data[$key]['totoal_price'] = $data[$key]['price']  * $item->number;
                }
            }
        } 
        
        $fc = new FullCut();
        $discount_data = $fc->getDataFromRedis();
        
        return $this->render('cart',['data'=>$data,'fullcut'=>$discount_data['desc']]);
    }
  
    /**
     * 添加购物车
     */
    public function actionAddCart()
    {        
        $msg = ['flag'=>false,'msg'=>'','data'=>['number'=>0],'errCode'=>''];
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
       
        $params =Yii::$app->request->post();//['bestry_uid'=>$this->bestry_uid,'goods_id'=>66,'product_id'=>225,'number'=>2] ;
        
        if(!$this->bestry_uid) {
            $msg['msg'] = '请登录后继续操作';
            $msg['errCode'] = '4001';
            return $msg;
        }
        
        $params['bestry_uid'] = $this->bestry_uid;
        
        $model = new Cart();
        
        if($model->load($params,'') && !$model->validate()) {
            if($model->hasErrors('goods_id')) {
                $msg['msg'] =$model->getErrors('goods_id');
                return $msg;
            }
            if($model->hasErrors('product_id')) {
                $msg['msg'] =$model->getErrors('product_id');
                return $msg;
            }
            if($model->hasErrors('number')) {
                $msg['msg'] =$model->getErrors('number');
                return $msg;
            }

        }
        
        //2000w -4000w不可以加入购物车
        if($model->product_id > 20000000 && $model->product_id < 40000000){
            $msg['msg'] = '该商品不能加入购物车';
            $msg['number'] = 1;
            return $msg;
        }
        
        if($model->number < 1) {
            $msg['msg'] = '商品购买数量不能小于1';
            $msg['number'] = 1;
            return $msg;
        }
               
        $msginfo =  $model->validateLimit();
        
        if(!$msginfo['flag']) {
            return $msginfo;
        }
        
        //查询当前商品在购物车是否存在
        $affect_rows = false;
        $cart_num = 0;
        $cart_info = Cart::find()->where(['bestry_uid'=>$this->bestry_uid,'goods_id'=>$model->goods_id,'product_id'=>$model->product_id])->one();
        
        //修改购物车商品数量
        if(!empty($cart_info) && $cart_info->number > 0) {
            
            $cart_num = $cart_info->number;
            
            $cart_info->number = $cart_info->number + $model->number;
            
            //查询库存信息
            $stockInfo = ProductStock::findByProductId($cart_info->product_id);
            if($cart_info->number > $stockInfo['stock'] ) {
                $msg['msg'] = '库存不足，请重新选择商品数量';
                $msg['number'] = $stockInfo['stock'];
                return $msg;
            }
            
            $cart_info->update_time = date("Y-m-d H:i:s");
            
            $affect_rows = $cart_info->save();
        } else {
            $model->create_time = date("Y-m-d H:i:s");
            $affect_rows = $model->save();
        }
        
        if(!$affect_rows) {
            $msg['msg'] = '加入购物车失败';
            $msg['number'] = $model->number;
            return $msg;
        }
        $msg['flag'] = true;
        $msg['msg'] = '加入购物车成功';
        $msg['number'] = $model->number + $cart_num;
        return $msg;
    }
    
    /**
     * 删除购物车商品[单个删除，多个删除]
     */
    public function actionDelCart()
    {
        $msg = [
            'flag' => false,
            'msg' => '',
            'order_amount' => '0.00',//总计RMB
            'try_coin' => 0,//总计试豆
            'reduce_amount'=>'0.00'
        ];
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $cartIds = Yii::$app->request->post('cartIds', ''); // 主键ids
        $selected_cartids = self::cartIdsProc(Yii::$app->request->post('selectedIds', '')); //当前选中的cart_ids
        if(!$this->bestry_uid) {
            $msg['msg'] = '请登录后继续操作';
            return $msg;
        }
        if (empty($cartIds)) {
            $msg['msg'] = '您的购物车中没有此商品';
            return $msg;
        }
        
        if (! preg_match('/^[\d,]+$/', $cartIds)) {
            $msg['msg'] = '参数错误';
            return $msg;
        }
        
        //去除非法字符
        $cartIds = trim(preg_replace('/,+/', ',', $cartIds),',');
        
        $cartInfos = Cart::find()->where('cart_id in ('.$cartIds.')')->all();
        
        if(!$cartInfos) {
            $msg['msg'] = '您的购物车中没有此商品';
            return $msg;
        }
        
        //根据条件删除购物车
        if(!Cart::deleteAll('cart_id in ('.$cartIds.')')){
            $msg['msg'] = '删除失败';
            return $msg;
        }
        
        //计算当前选中的总价格
        if(!empty($selected_cartids)) {
            
            $order = new Order();
            $order->bestry_uid = $this->bestry_uid;
            $order->cart_ids = $selected_cartids;
            
            $order->validateCustom();
            OrderDiscount::discount($order);
            $order->format();
            
            $gdms = $order->getDiscountMsg();
            $gdm = array_filter(
                $gdms, function ($item) {
                    /** @var \common\models\OrderDiscount $item */
                    if ($item->type == \services\models\discount\FullCut::shortClassName()) {
                        return true;
                    }
                    return false;
                });
            if (!empty($gdm)) {
                $gdm = array_pop($gdm);
                $fullcut = $gdm->describe;
            }
            
            $msg['try_coin'] = $order->try_coin;
            $msg['order_amount'] = $order->order_amount;
            $msg['reduce_amount'] = $order->reduce_amount;
           
        }
        $msg['flag'] = true;
        $msg['msg'] = '删除成功';
        
        return $msg;
    }
    
    /**
    * 修改购物车数量
    */
    public function actionChangeNum()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $msg = [
            'flag' => false,
            'msg' => '',
            'sumPrice' => '0.00',//小计RMB
            'sumSd' => 0,//小计试豆
            'order_amount' => '0.00',//总计RMB
            'try_coin' => 0,//总计试豆
            'number' => 0,//数量
            'reduce_amount'=>'0.00'
        ];

        $cartId = intval(Yii::$app->request->post('cartId', '')); // 购物车id
        $number = intval(Yii::$app->request->post('number', '')); // 数量
        $selected_cartids = self::cartIdsProc(Yii::$app->request->post('selectedIds', '')); //当前选中的cart_ids
        if(!$this->bestry_uid) {
            $msg['msg'] = '请登录后继续操作';
            return $msg;
        }
        
        if(!$cartId) {
            $msg['msg'] = '您的购物车中没有此商品';
            return $msg;
        }
        //查询购物车是否有商品
        $cartInfo = Cart::findOne(['cart_id'=>$cartId]);
        if(!$cartInfo) {
            $msg['msg'] = '您的购物车中没有此商品';
            return $msg;
        }
        
        $model = new  Cart();
        $model->product_id = $cartInfo->product_id;
        $model->goods_id = $cartInfo->goods_id;
        $model->number = $number;
        $model->bestry_uid = $cartInfo->bestry_uid;
        
        $msginfo =  $model->validateLimit();
        
        if(!$msginfo['flag']) {
            return $msginfo;
        }
        //修改购物车数量
        $cartInfo->number = $number;
        $cartInfo->update_time = date("Y-m-d H:i:s");
        
        if(!$cartInfo->save()) {
            $msg['msg'] = '加入购物车失败';
            $msg['msg']['data']['number'] = $number;
            return $msg;
        }
        
        $fc = new FullCut();
        $discount_data = $fc->getDataFromRedis();
        if (empty($discount_data)) {
            $fullcut = '';
        } else {
            $fullcut = $discount_data['desc'];
        }
        
        //计算小计
        $sumPrice = $sumSd = 0;
        $productInfo = Product::findByProductId($cartInfo->product_id);
        if($productInfo['price_type'] == Product::$_PRICE_TYPE_RMB) {
            $sumPrice = ($productInfo['sale_price'] * $cartInfo->number);
        }else {
            $sumSd = ($productInfo['try_price'] * $cartInfo->number);
        }
        
        $msg['sumSd'] = $sumSd;
        $msg['sumPrice'] = $sumPrice;
        
        
        //计算当前选中的总价格
        if(!empty($selected_cartids)) {
            
            $order = new Order();
            $order->bestry_uid = $this->bestry_uid;
            $order->cart_ids = $selected_cartids;
            
            $order->validateCustom();
            OrderDiscount::discount($order);
            $order->format();
            $gdms = $order->getDiscountMsg();
            $gdm = array_filter(
                $gdms, function ($item) {
                    /** @var \common\models\OrderDiscount $item */
                    if ($item->type == \services\models\discount\FullCut::shortClassName()) {
                        return true;
                    }
                    return false;
                });
            if (!empty($gdm)) {
                $gdm = array_pop($gdm);
                $fullcut = $gdm->describe;
            } 
            
           $msg['try_coin'] = $order->try_coin;
           $msg['order_amount'] = $order->order_amount;
           $msg['reduce_amount'] = $order->reduce_amount;
           
        }
        
        $msg['flag'] = true;
        $msg['msg'] = '加入购物车成功';
        $msg['fullcut'] = $fullcut;
        $msg['number'] = $number;
        
        return $msg;
         
    }
    
    
    /**
     * 勾选复选框 返回价格
     */
    public function actionSelectSum()
    {
        $msg = [
            'flag' => false,
            'msg' => '',
            'order_amount' => '0.00',//总计RMB
            'try_coin' => 0,//总计试豆
            'reduce_amount'=>'0.00'
        ];
    
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $selected_cartids = self::cartIdsProc(Yii::$app->request->post('cart_ids', '')); //当前选中的cart_ids
          
    
        if(!$this->bestry_uid) {
            $msg['msg'] = '请登录后继续操作';
            return $msg;
        }
        
        $fc = new FullCut();
        $discount_data = $fc->getDataFromRedis();
        if (empty($discount_data)) {
            $fullcut = '';
        } else {
            $fullcut = $discount_data['desc'];
        }
        
         //计算当前选中的总价格
        if(!empty($selected_cartids)) {
            $order = new Order();
            $order->bestry_uid = $this->bestry_uid;
            $order->cart_ids = $selected_cartids;
            
            $order->validateCustom();
            OrderDiscount::discount($order);
            $order->format();
            $gdms = $order->getDiscountMsg();
            $gdm = array_filter(
                $gdms, function ($item) {
                    /** @var \common\models\OrderDiscount $item */
                    if ($item->type == \services\models\discount\FullCut::shortClassName()) {
                        return true;
                    }
                    return false;
                });
            if (!empty($gdm)) {
                $gdm = array_pop($gdm);
                $fullcut = $gdm->describe;
            } 
            
           $msg['try_coin'] = $order->try_coin;
           $msg['order_amount'] = $order->order_amount;
           $msg['reduce_amount'] = $order->reduce_amount;
             
        }
        
        $msg['fullcut'] = $fullcut;
        $msg['flag'] = true;
        $msg['msg'] = 'success';
        
        return $msg;
         
    }
  
}